
package com.jiangtai.smartbox.ui

import android.annotation.SuppressLint
import android.content.ContentValues
import android.content.Intent
import android.os.Handler
import android.provider.Settings
import android.util.Log
import com.google.gson.reflect.TypeToken
import com.hjq.toast.ToastUtils
import com.jiangtai.smartbox.R
import com.jiangtai.smartbox.base.BaseActivity
import com.jiangtai.smartbox.base.UidBean
import com.jiangtai.smartbox.bean.BoxBean
import com.jiangtai.smartbox.bean.FaceInfoUploadBean
import com.jiangtai.smartbox.bean.FaceResponseBean
import com.jiangtai.smartbox.bean.mqtt.MqttResponseBean
import com.jiangtai.smartbox.bean.mqtt.Person
import com.jiangtai.smartbox.bean.mqtt.Task
import com.jiangtai.smartbox.bean.mqtt.TaskStateBean
import com.jiangtai.smartbox.bean.request.PersonInfoBean
import com.jiangtai.smartbox.bean.request.PersonsBean
import com.jiangtai.smartbox.bean.request.SearchSuccessReq
import com.jiangtai.smartbox.bean.response.FaceInfoBean
import com.jiangtai.smartbox.constant.Constant
import com.jiangtai.smartbox.dialog.ConfirmDialog
import com.jiangtai.smartbox.dialog.LoginDialog
import com.jiangtai.smartbox.event.OpenBoxEvent
import com.jiangtai.smartbox.event.SearchBoxEvent
import com.jiangtai.smartbox.net.CallbackListObserver
import com.jiangtai.smartbox.net.MyRetrofit
import com.jiangtai.smartbox.net.ThreadSwitchTransformer
import com.jiangtai.smartbox.service.MyService
import com.jiangtai.smartbox.util.*
import com.jinyx.mqtt.*
import com.jinyx.mqttdemo.*
import dismissLoading
import kotlinx.android.synthetic.main.activity_main.*
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody
import org.greenrobot.eventbus.EventBus
import org.litepal.LitePal
import showLoading
import showToast
import java.util.*


@SuppressLint("HardwareIds")
class MainActivity : BaseActivity() {
   // private var host = "tcp://221.226.11.218:22883" //todo :测试环境服务器地址
    private var host = "tcp://26.88.124.15:1883" //todo :正式环境服务器地址
    private var locIP: String by Preference(Constant.LOC_IP, "")//本机IP
    private var updateTime: Long by Preference(Constant.UPDATE_TIME, 0L)//最近盘存时间
    private var watchNum: Int by Preference(Constant.WATCH_NUM, 0)//表的数量
    private var currentTaskId: String by Preference(Constant.CURRENT_TASK_ID, "")//当前任务
    private var isUploaded: Boolean by Preference(Constant.IS_UPLOADED, false)//是否上传过人脸
    private var deviceSn: String? by Preference(Constant.DEVICE_SN, "")//设备标识611F010T00100291
    private var TOPIC_GET_TASK = ""
    private var TOPIC_TASK_STATE = ""
    private var TOPIC_TASK_UPLOAD = ""
    private var TOPIC_GET_ALL_PERSON = ""
    private var TopicReceive = ""

    private var personInfoList = mutableListOf<PersonInfoBean>()
    private var listPersons = mutableListOf<Person>()


    companion object{
      val  TAG = "MainActivity"
    }
    private val mAndroidId: String by lazy {
        Settings.Secure.getString(contentResolver, Settings.Secure.ANDROID_ID)
    }
    private lateinit var mqttHelper: IMqtt

    private var listBox = mutableListOf<BoxBean>()

    private var  deleteCount = 0
    private var  addcount = 0

    private var handler = Handler()

    override fun attachLayoutRes(): Int = R.layout.activity_main
    private var isChecking = false
    override fun initData() {
        listBox = LitePal.findAll(BoxBean::class.java)
        if (listBox.isEmpty()){
            //盘点,初始化柜子对象
            for (i in 1..72) {
                if (i == 3 || i == 7 || i == 11 || i == 15) {
                    if (i < 10) {
                        listBox.add(BoxBean("", true, false, false))
                        listBox.add(BoxBean("", true, false, false))
                        listBox.add(BoxBean("", true, false, false))
                    } else {
                        listBox.add(BoxBean("", true, false, false))
                        listBox.add(BoxBean("", true, false, false))
                        listBox.add(BoxBean("", true, false, false))
                    }
                }
                if (i < 10) {
                    listBox.add(BoxBean("0${i}", true, false, true))
                } else {
                    listBox.add(BoxBean("${i}", true, false, true))
                }
            }
            listBox.forEach {
                it.save()
            }
        }

        //服务未启动,启服务
        if (!ServiceUtil.isServiceRunning("com.jiangtai.smartbox.service.MyService")){
            val intent = Intent(this, MyService::class.java)
            startService(intent)
        }

        Log.e("Time", "${(System.currentTimeMillis() - updateTime) / (1000 * 60)}分")
        if ((System.currentTimeMillis()-updateTime)>1000*60*60*48){//每次打开  距上次盘点超过2天  就盘点一次
            showLoading()
            val contentValues = ContentValues()
            contentValues.put("empty", true)
            LitePal.updateAll(BoxBean::class.java, contentValues, "empty=?", "0")
            Log.e("tt", "isChecking = $isChecking")
            Thread{
                isChecking = true
                while (isChecking) {
                    for (box in listBox) {
                        if (box.useful) {
                            EventBus.getDefault().post(SearchBoxEvent(box))
                            Thread.sleep(50)
                        }
                    }
                    isChecking = false
                    handler.postDelayed(Runnable {
                        val watchList = LitePal.where("empty = ?", "0").find(BoxBean::class.java)
                        Log.e(
                            "Watch",
                            "watchNum = ${watchList.size},EmptyNum = ${72 - watchList.size}"
                        )
                        watchNum = watchList.size
                        //记录当前时间   每次间隔2个小时盘存一次
                        updateTime = System.currentTimeMillis()
                        Log.e("Thread", "threat =${Thread.currentThread().name}")
                        dismissLoading()
                    }, 12000)
                }
            }.start()
        }


    }

    private val PERMISS_REQUEST_CODE = 0x100

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String>,
        grantResults: IntArray
    ) {
        if (requestCode == PERMISS_REQUEST_CODE){
               LitePal.getDatabase()
        }
    }

    override fun initView() {
        //请求权限
        if (checkPermissions(arrayOf(android.Manifest.permission.WRITE_EXTERNAL_STORAGE))) {
                  LitePal.getDatabase()
        } else {
            requestPermission(
                arrayOf(android.Manifest.permission.WRITE_EXTERNAL_STORAGE),
                PERMISS_REQUEST_CODE
            )
        }
        //本地ip
        val currentIp = CommonUtil.getIpAddressString()
        Log.e("IP", "ip==$currentIp")
        if (currentIp != locIP) {
            locIP = currentIp
            MyRetrofit.resetInstance()
        }
        //本机deviceSN  MQTT
        initMQTT()
       // addPerson()    //添加人员
       //searchPeople()  //搜索人脸底库人员
    }





    private fun searchPeople() {
        val searchAll = MyRetrofit.instance.api.searchAll()
        searchAll.compose(ThreadSwitchTransformer()).subscribe(object :
            CallbackListObserver<String>() {
            override fun onSucceed(t: String) {
                val listType = object : TypeToken<List<UidBean?>?>() {}.type
                val listUser = ToJsonUtil.getInstance().fromJson<List<UidBean>>(t,listType)
                ToastUtils.show("人脸图库现有${listUser.size}张人脸数据")
                listUser.forEach {
                    val find = LitePal.where("uid = ?", it.uid.toString()).find(PersonInfoBean::class.java)
                    if (find.isNotEmpty() && find[0].uploadPicState == 0){//新成功的保存
                        find[0].uploadPicState = 1
                        find[0].save()
                    }
                }
            }

            override fun onFailed() {

            }

        })
    }

    private var myUrl="http://59.110.230.192//uploadtemp/image/2021/6/2fbaa60cdc6e49f88da7c2ffdfd430c1.jpg"
    private var  url1 ="http://5b0988e595225.cdn.sohucs.com/images/20190908/e8820b18cd2d4760b16dcce1b3b27620.jpeg"
    private var  url2 ="http://59.110.230.192//uploadtemp/image/2021/6/94507ab6f11f44c1aa29392e25989e0a.jpeg"

    //注册人脸数据
    private var isdownload = false//是否在下载人脸
    private fun addPerson() {
        val list = mutableListOf<FaceInfoUploadBean>()
        list.clear()
        val newUsers = LitePal.where("uploadPicState = ?", "0").find(PersonInfoBean::class.java)
        val filter = newUsers.filter {
            it.picture.isNotEmpty()
        }
        filter.forEach {
            list.add(FaceInfoUploadBean(it.uid,it.picture,it.sex,it.name))
        }
        ToastUtils.show("准备上传${list.size}张人脸")
        if (!isdownload){
            Thread {
                isdownload=true
                val listPackage =  averageAssignFixLength(list,1)
                for (listItem in listPackage){
                    askServerForAddPersonList(listItem)
                    Thread.sleep(1000)
                    //  Log.e("addSize","包大小=${listItem.size}")
                }
                runOnUiThread {
                    isdownload = false
                    ToastUtils.show("人脸信息已下发完成")
                }
            }.start()
        }else{
            ToastUtils.show("正在下发人脸中，请稍后")
        }
    }
    private fun <T> averageAssignFixLength(source: List<T>?, splitItemNum: Int): List<List<T>> {
        val result = ArrayList<List<T>>()
        if (source != null && source.run { isNotEmpty() } && splitItemNum > 0) {
            if (source.size <= splitItemNum) {
                // 源List元素数量小于等于目标分组数量
                result.add(source)
            } else {
                // 计算拆分后list数量
                val splitNum = if (source.size % splitItemNum == 0) source.size / splitItemNum else source.size / splitItemNum + 1

                var value: List<T>? = null
                for (i in 0 until splitNum) {
                    if (i < splitNum - 1) {
                        value = source.subList(i * splitItemNum, (i + 1) * splitItemNum)
                    } else {
                        // 最后一组
                        value = source.subList(i * splitItemNum, source.size)
                    }

                    result.add(value)
                }
            }
        }

        return result
    }

    private fun askServerForAddPersonList(list: List<FaceInfoUploadBean>) {
        val requestBody =
            RequestBody.create(
                "application/json; charset=utf-8".toMediaTypeOrNull(),
                ToJsonUtil.getInstance().toJson(list)
            )
        val addPersonInfo = MyRetrofit.instance.api.addPersonInfo(requestBody)
        addPersonInfo.compose(ThreadSwitchTransformer())
            .subscribe(object : CallbackListObserver<String>() {
                override fun onSucceed(t: String) {
                    Log.e("Retrofit", "result= $t")
                }

                override fun onFailed() {

                }
            })
    }

    //设备上报  获取最新任务数据
    private fun getTaskBeanMessage() {
        val data = Data(System.currentTimeMillis().toString())
        val bean = ReqBean(data, MD5Utils.getMyUUID(), System.currentTimeMillis())
        mqttHelper.pubMessage(
            TOPIC_GET_TASK,
            ToJsonUtil.getInstance().toJson(bean).toByteArray()
        )
    }

    //设备上报  获取任务状态
    private fun getTaskState(taskId: String){
        val data = DataTaskId(taskId)
        val bean = ReqTaskStateBean(data, MD5Utils.getMyUUID(), System.currentTimeMillis())
        mqttHelper.pubMessage(
            TOPIC_TASK_STATE,
            ToJsonUtil.getInstance().toJson(bean).toByteArray()
        )
    }

    //设备上报  获取所有人员信息
   private fun getAllPersonInfo(){
           val data = DataPersonId("")
           val bean = ReqAllPersonInfoBean(data, MD5Utils.getMyUUID(), System.currentTimeMillis())
        mqttHelper.pubMessage(
            TOPIC_GET_ALL_PERSON,
            ToJsonUtil.getInstance().toJson(bean).toByteArray()
        )
   }

    private fun initMQTT() {
        deviceSn = CommonUtil.getSNCode()
        Log.e("MainActivity", "deviceSn = $deviceSn")
        tv_address.text = "智慧训练中心智能表柜 \ndeviceSn:$deviceSn"
        TOPIC_GET_TASK = "/tianbo_wearable_locker/$deviceSn/event/get_task_detail"
        TOPIC_TASK_STATE = "/tianbo_wearable_locker/$deviceSn/event/task_status_list"
        TOPIC_TASK_UPLOAD = "/tianbo_wearable_locker/$deviceSn/event/wearable_data_report"
        TopicReceive = "/tianbo_wearable_locker/$deviceSn/function/invoke"
        TOPIC_GET_ALL_PERSON="/tianbo_wearable_locker/$deviceSn/event/get_pty_list"

        val options = MqttOptions(
            serviceUrl = host,
            username = "$deviceSn|${System.currentTimeMillis()}",
            password = MD5Utils.stringToMD5("$deviceSn|${System.currentTimeMillis()}|$deviceSn"),
            clientId = "$deviceSn",
            willTopic = "will/android",
            willMsg = "I'm Died - $mAndroidId"
        )
        mqttHelper = MqttHelper(this, options)
        mqttHelper.addOnMsgListener(object : OnMqttMsgListener {
            override fun onPubMessage(payload: ByteArray) {
                Log.e("tag", "发送成功 ${String(payload)}")
            }

            override fun onSubMessage(topic: String, payload: ByteArray) {
                val jsonStr = String(payload)
                Log.e("MQTT", "jsonStr=$jsonStr")
                if (jsonStr.isNotEmpty()) {
                    val mqttBean =
                        ToJsonUtil.getInstance().fromJson(jsonStr, MqttResponseBean::class.java)
                    Log.e("function", "function ==${mqttBean.function}")
                    when (mqttBean.function) {
                        "get_task_detail_response" -> {//最新任务数据回调
                            if (mqttBean.inputs.isNotEmpty() && mqttBean.inputs[0].value.isNotEmpty()) {
                                val taskJsonStr = mqttBean.inputs[0].value
                              //  Log.e("MQTT", "taskJsonStr=${mqttBean.inputs[0].value}")
                                val taskBean =
                                    ToJsonUtil.getInstance().fromJson(taskJsonStr, Task::class.java)
                                currentTaskId = taskBean.taskId
                             //   Log.e("MQTT", "当前任务ID=${currentTaskId}")
                                val listCabinets = taskBean.cabinets
//                                listCabinets.forEach {
//                                    Log.e(
//                                        "MQTT",
//                                        "柜子名称==${it.cabinetNm},柜子编号==${it.cabinetNo},该柜子人数=${it.persons.size}}"
//                                    )
//                                }

                                if (listCabinets.isNotEmpty()) {
                                    listCabinets.forEach {
                                        it.persons.forEach { person ->
                                            person.cabinetNo = it.cabinetNo
                                            person.cabinetNm = it.cabinetNm
                                        }
                                        listPersons.addAll(it.persons)
                                    }
                                }
                            }

                            Log.e("MQTT", "总人数=${listPersons.size}")
                            listPersons.forEach {
                                Log.e(
                                    "MQTT",
                                    "人员信息=${it.personNm},人员id=${it.personId},柜子No=${it.cabinetNo}"
                                )
                                val persons = LitePal.where("personId = ?", it.personId)
                                    .find(PersonInfoBean::class.java)
                                // 根据任务人员与所有人员 设置人员的状态  存数据库
                                if (persons.isNotEmpty()) {
                                    persons[0].reservation = 1 //已预约
                                    persons[0].cabinetNo = it.cabinetNo //所在柜子
                                    persons[0].cabinetNm = it.cabinetNm//所在柜子名
                                    persons[0].save()//更新数据库
                                } else {
                                    Log.e("MQTT", "任务里的人未在全员表中找到,personId = ${it.personId}")
                                }
                            }

                        }

                        "task_status_list_response" -> {//查询任务状态,已结束就拉取新任务,清空当前任务(当前预约人)
                            if (mqttBean.inputs.isNotEmpty() && mqttBean.inputs[0].value.isNotEmpty()) {
                                val taskJsonStr = mqttBean.inputs[0].value
                                Log.e("MQTT", "taskJsonStr=${mqttBean.inputs[0].value}")
                                val taskStateBean =
                                    ToJsonUtil.getInstance().fromJson(
                                        taskJsonStr,
                                        TaskStateBean::class.java
                                    )
                                if (taskStateBean.flag) {//已完成
                                    currentTaskId = ""//清空当前任务
                                    // 清除预约人标识
                                    val cv = ContentValues()
                                    cv.put("reservation", "0")
                                    LitePal.updateAll(PersonInfoBean::class.java, cv)
//                                    val takedList = LitePal.where("takeState = ?", "1").find(PersonInfoBean::class.java)
//                                    Log.e("MQTT", "任务结束,表全部入柜,更新全员数据")
//                                    if (takedList.isEmpty()) {
//                                        getAllPersonInfo()
//                                    }else{
//                                        ToastUtils.show("还有表未还")
//                                    }

                                } else {//未完成 不做处理

                                }
                            }
                        }

                        "get_pty_list_response" -> {//所有人员信息
                            if (mqttBean.inputs.isNotEmpty() && mqttBean.inputs[0].value.isNotEmpty()) {
                                val userJsonStr = mqttBean.inputs[0].value
                                Log.e("MQTT", "userJsonStr=${userJsonStr}")
                                val personsBean = ToJsonUtil.getInstance().fromJson<PersonsBean>(
                                    mqttBean.inputs[0].value,
                                    PersonsBean::class.java
                                )
                                val listUser = personsBean.persons
//                                val listType = object : TypeToken<List<PersonInfoBean?>?>() {}.type
//                                val listUser = ToJsonUtil.getInstance().fromJson<List<PersonInfoBean>>(personsBean.persons,listType)
                                Log.e("MQTT", "用户总数量=${listUser.size}")
                                listUser.forEach {
                                    val finds = LitePal.where("uid = ?", it.uid.toString()).find(PersonInfoBean::class.java)
                                    if (finds.isEmpty()){//库中没有这个人  增量更新
                                          it.save()
                                    }else{//有的话  更新人脸照片
                                        finds[0].picture = it.picture
                                        finds[0].save()
                                    }
                                }
                                searchPeople()
                                handler.postDelayed(Runnable {
                                    if(!isUploaded){
                                        isUploaded = true
                                        addPerson()
                                    }
                                },2000)


//                                val findAll = LitePal.findAll(PersonInfoBean::class.java)
//
//                                if (findAll.size == listUser.size){
//                                    ToastUtils.show("人员基础库未发生变化")
//                                }else{
//                                    Log.e("MQTT", "更新人员基础库")
//                                    if (listUser.isNotEmpty()) {
//                                        listUser.forEach {
//                                            it.save()
//                                        }
//                                         addPerson()
//                                    }
//                                    ToastUtils.show("人脸信息开始更新")
//                                }
                                //全员信息更新完毕  去拉取任务
                                getTaskBeanMessage()
                            }
                        }
                        else -> {

                        }
                    }
                }
            }

        })
        mqttHelper.addOnStatusChangeListener(object : OnMqttStatusChangeListener {
            override fun onChange(state: MqttStatus, throwable: Throwable?) {
                /**
                 *   MQTT 连接状态改变:
                 *  [MqttStatus.SUCCESS]    // 连接成功
                 *  [MqttStatus.FAILURE]    // 连接失败
                 *  [MqttStatus.LOST]   // 连接中断
                 */
                Log.e("MqttState", "$state")
                if (state == MqttStatus.SUCCESS) {
                    mqttHelper.subscribe("$TopicReceive")
                    //连接成功后先判断有无当前任务,如果无就拉取新任务,
                    // 否则就看当前任务是否结束,未结束就不做操作,
                    // 结束就去拉取新任务,并将当前任务清空
                    //当前任务为空,获取全员信息-->获取任务信息
                    //任务结束,获取最新任务
                    //更新全员信息  当前任务已结束  且全部还表  删除再更新
                    if (currentTaskId == "") {
                        ToastUtils.show("请求更新人员信息...")

                        getAllPersonInfo()
                    } else {
                        ToastUtils.show("请求当前任务状态...")
                        getTaskState(currentTaskId)
                    }
                } else {
                    ToastUtils.show("MQTT服务连接失败！！！")
                }
            }

        })
        mqttHelper.connect()


    }

    private var isopenning =false

    override fun initListener() {


        iv_put.setOnClickListener {//进入归还手表
            Intent(this, PutWatchActivity::class.java).apply {
                startActivity(this)
            }
        }

        iv_check.setOnClickListener {
            Intent(this, BoxCheckActivity::class.java).apply {
                startActivity(this)
            }
        }

        iv_open.setOnClickListener {
            val packageManager = packageManager
            val intent = packageManager.getLaunchIntentForPackage("com.tongyue.facerecognition")
            startActivity(intent)
            //轮询查询识别成功的人 识别成功后  调到成功页
            val startTime = DateUtil.getCurrentTime()
            //循环查接口
            searching = true
            checkResult(startTime)
        }

        iv_head.setOnClickListener {
            //发送信息
            addcount++
            if (addcount == 10){
                val addDialog  = ConfirmDialog(this,"确定添加新的人脸数据？")
                addDialog.show()
                addDialog.setonConfirmListener(object :ConfirmDialog.OnConfirmListener{
                    override fun onConfirm(sure: Boolean) {
                        if (sure){
                             addPerson()
                             ToastUtils.show("开始添加人脸数据...")
                        }else{

                        }
                        addcount=0
                        addDialog.dismiss()
                    }

                })
            }else{
                searchPeople()
            }

        }



        iv_desc.setOnClickListener {
            deleteCount++
            if (deleteCount==10){
                val delDialog  = ConfirmDialog(this,"确定删除本地人脸数据？")
                delDialog.show()
                delDialog.setonConfirmListener(object :ConfirmDialog.OnConfirmListener{
                    override fun onConfirm(sure: Boolean) {
                        if (sure){
                            deleteAllPeopleFace()
                            ToastUtils.show("删除人脸数据...")
                        }
                        deleteCount=0
                        delDialog.dismiss()
                    }

                })
            }
        }


        iv_admin.setOnClickListener {
            val dialog = LoginDialog(this)
            dialog.show()
            dialog.setonConfirmListen(object : LoginDialog.OnConfirmListener {
                override fun onConfirm(success: Boolean) {
                    dialog.dismiss()
                    if (success) {
                        //开柜子
                        showLoading()
                        Thread {
                            isopenning = true
                            while (isopenning) {
                                for (box in listBox) {
                                    if (box.useful) {
                                        //openBox(box)
                                        EventBus.getDefault().post(OpenBoxEvent(box))
                                        Thread.sleep(50)
                                    }
                                }
                                isopenning = false
                                runOnUiThread {
                                    val watchList =
                                        LitePal.where("empty = ?", "0").find(BoxBean::class.java)
                                    Log.e(
                                        "Watch",
                                        "watchNum = ${watchList.size},EmptyNum = ${72 - watchList.size}"
                                    )
                                    watchNum = watchList.size
                                    //记录当前时间   每次间隔2个小时盘存一次
                                    updateTime = System.currentTimeMillis()
                                    dismissLoading()
                                }
                            }
                        }.start()

                    } else {
                        ToastUtils.show("账号密码错误")
                    }

                }

            })
        }

    }

    private fun deleteAllPeopleFace() {
        val deleteUser = MyRetrofit.instance.api.deleteAllFaceInfo()
        deleteUser.compose(ThreadSwitchTransformer())
            .subscribe(object : CallbackListObserver<String>() {
                override fun onSucceed(t: String?) {
                    val faceResponseBean = ToJsonUtil.getInstance().fromJson<FaceResponseBean>(t, FaceResponseBean::class.java)
                    if (faceResponseBean.code == 1){
                        ToastUtils.show("删除所有人脸成功")
                    }else{
                        ToastUtils.show("删除所有人脸失败，Msg=${faceResponseBean.msg}")
                    }

                }

                override fun onFailed() {
                    ToastUtils.show("删除所有人脸接口onFailed")
                }
            })
    }

    private var searching = false

    override fun onResume() {
        super.onResume()
        searching = false
    }



    override fun onDestroy() {
        searching = false
        mqttHelper.disConnect()
        //destroySerial()
        super.onDestroy()
    }


    private fun checkResult(startTime: String) {
        val bean = SearchSuccessReq(DateUtil.getCurrentTime(), 1, 1, startTime)
        val requestBody =
            RequestBody.create(
                "application/json; charset=utf-8".toMediaTypeOrNull(),
                ToJsonUtil.getInstance().toJson(
                    bean
                )
            )
        val searchCheckedSuccessPersonList =
            MyRetrofit.instance.api.searchCheckedSuccessPersonList(requestBody)
        searchCheckedSuccessPersonList.compose(ThreadSwitchTransformer()).subscribe(object :
            CallbackListObserver<String>() {
            override fun onSucceed(t: String?) {
                val listType = object : TypeToken<List<FaceInfoBean?>?>() {}.type
                val list = ToJsonUtil.getInstance().fromJson<List<FaceInfoBean>>(
                    t, listType
                )
                if (list.isNotEmpty()) {
                    searching = false//识别成功
                    //识别的人是哪个
                    val faceInfoBean = list.last()
                    ToastUtils.show("人脸信息id=${faceInfoBean.uid},人名 =${faceInfoBean.name}")
                    Log.e("Face", "人脸信息id==${faceInfoBean.uid},人名==${faceInfoBean.name}")
                    val perList = LitePal.where("uid=?", faceInfoBean.uid.toString())
                        .find(PersonInfoBean::class.java)
//                    if (perList.isEmpty()){//id 没找到   就找到对应的人
//                        perList = LitePal.where("name=?", faceInfoBean.name)
//                                .find(PersonInfoBean::class.java)
//                    }
                    if (perList.isNotEmpty()) {
                        //是否是预约人,并在此柜,是开柜
                        //不是预约人,开柜 普通柜数量-1
                        val personInfoBean = perList[0]
                        Log.e("Face", "personId=${personInfoBean.personId}")
                        if (personInfoBean.takeState == 1) {
                            ToastUtils.show("您已取表,请归还后再取表")
                            Intent(this@MainActivity, MainActivity::class.java).apply {
                                startActivity(this)
                            }
                            return
                        }
                        if (personInfoBean.reservation == 1) {
                            //不是此柜子的预约人员
                            if (personInfoBean.cabinetNo != deviceSn) {
                                ToastUtils.show("请到柜子 ${personInfoBean.cabinetNm}处取表")
                                Intent(this@MainActivity, MainActivity::class.java).apply {
                                    startActivity(this)
                                }
                            } else {
                                if (watchNum > 0) {
                                    //开柜
                                    val intent = Intent(
                                        this@MainActivity,
                                        BoxOpenSuccessActivity::class.java
                                    )
                                    intent.putExtra("personId", personInfoBean.personId)
                                    intent.putExtra("takeWatch", true)
                                    startActivity(intent)
                                } else {
                                    ToastUtils.show("腕表已全部取完")
                                    //Log.e("FACE", "腕表已全部取完")
                                }
                            }

                        } else {
                            //非预约人(有空余表的情况取表)  或者 在此柜子的预约人员
                            //获取未取表的预约人数量
                            val fixWatchList = LitePal.where(
                                "reservation = ? and takeState = ?",
                                "1",
                                "0"
                            )
                                .find(PersonInfoBean::class.java)
                            if (watchNum - fixWatchList.size > 0) {
                                //开柜
                                val intent = Intent(
                                    this@MainActivity,
                                    BoxOpenSuccessActivity::class.java
                                )
                                intent.putExtra("personId", personInfoBean.personId)
                                intent.putExtra("takeWatch", true)
                                startActivity(intent)

                            } else {
                                ToastUtils.show("该柜子腕表已全部预约,暂无可用表")
                                Log.e("FACE", "该柜子腕表已全部预约,暂无可用表")
                                Intent(this@MainActivity, MainActivity::class.java).apply {
                                    startActivity(this)
                                }
                            }

                        }


                    } else {
                        ToastUtils.show("没有您的信息,请先录入系统")
                    }
                }else{
                    ToastUtils.show("人脸服务查找识别中......")
                }
                if (searching) {
                    checkResult(startTime)
                }

//                }
            }

            override fun onFailed() {
                Log.e("check", "识别onFailed")
                ToastUtils.show("人脸服务接口 onFailed")
            }

        })
    }

}